<?php


namespace App\Http\Admin\Controllers\V1;


use App\Http\Controllers\Controller;
use App\Libs\Common\Cache\ConfigCacheClass;
use App\Libs\Common\Cache\PermissionMenu;
use App\Libs\Common\Html\From;
use App\Libs\Common\LunarCalendar;
use App\Models\AdminLog;
use Illuminate\Support\Facades\DB;


class BasisController extends Controller
{

    protected $adminUser;
    protected $m = 'admin';//模块
    protected $v = 'v1'; // 版本
    protected $path_address='home/index'; // 链接地址
    protected $path_info; // 链接详情
    protected $query_string; // 请求参数
    protected $menuInfo;//菜单详情
    protected $backstageSet; // 后台站点信息

    public function __construct()
    {
        $this->middleware(function($request, $next){
            //登陆验证
            $this->adminUser = $request->user('admin');

            if (!$this->adminUser) {
                return $this->responseMsg('100000',false,'请登录',array('url'=>url('/')));
            }
            $this->adminUser->login_token = adminLoginToken($this->adminUser->username);
            $this->adminUser->login_url = adminLoginUrl($this->adminUser->username);

            $this->backstageSet = $this->backstageSet();  // 后台配置
            $this->_getPathInfo();//获取请求信息
            //当前请求菜单详情
            if(!in_array($this->path_address,$this->publicRequest())){
                $this->menuInfo = PermissionMenu::ifMenuName($this->v,$this->path_address);
                if ((!$this->menuInfo) && !in_array($this->path_address,PermissionMenu::publicMenu()) ) {
                    return $this->responseMsg('100010',false,'请求地址不存在,请添加!');
                }
                //检查请求权限
                if (empty(PermissionMenu::getPermission($this->v,$this->path_address))) {
                    return $this->responseMsg('100020',false,'没有权限');
                }
                //记录日志
                if (!empty($this->menuInfo) && $this->menuInfo->write_log == 1) {
                    $this->_saveLog($this->menuInfo->id);
                }
            }

            return $next($request);
        });
    }

    /**
     * Todo:: 获取请求信息 模块,控制器,方法
     */
    private function _getPathInfo()
    {
        $request_uri = explode('?', $_SERVER['REQUEST_URI']);
        if (isset($request_uri[1])) {
            $this->query_string = $request_uri[1];
        }
        $this->path_info = trim($request_uri[0], '/');
        if ($this->path_info) {
            $mca = explode('/', $this->path_info);
            if(count($mca) > 2){
                if($mca[0]){
                    unset($mca[0],$mca[1]);
                }else{
                    unset($mca[0],$mca[1],$mca[2]);
                }
                $this->path_address = implode('/',$mca);
            }
        }
    }

    /**
     * Todo:: 获取初始化配置
     * @return object
     */
    protected function backstageSet(){
        $config = [
            'backstage_name' => '后台管理系统',
            'backstage_icon_url' => '',
        ];
        $data = ConfigCacheClass::cacheConfigType('backstage_set');
        if($data){
            foreach ($data as $key=>$val){
                if($val->name == 'backstage_name'){
                    $config['backstage_name'] = $val->value;
                }
                if($val->name == 'backstage_icon_url'){
                    $config['backstage_icon_url'] = imageUrl($val->value);
                }
            }

        }
        return (object)$config;
    }

    /**
     * Todo:: 返回视图数据
     * @param array $data
     * @param string $tpl
     * @param int $isDefault 是否为默认
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function view($data = [], $tpl = '',$isDefault=1)
    {
        if (empty($tpl)) {
            $tpl = $this->m . '/'.$this->v.'/'. $this->path_address;
        }else{
            if($isDefault){
                $tpl = $this->m . '/'.$this->v.'/'.$tpl;
            }
        }
        $data = $data?$data:[];
        $data['_m'] = $this->m;
        $data['_v'] = $this->v;
        $data['_address'] = $this->path_address;
        //$data['module_id'] = $this->module_id;
        $data['admin_user'] = $this->adminUser;
        $data['backstage_set'] = $this->backstageSet;
        $data['menu_info'] = $this->menuInfo;
        $data['my_menu_html'] = PermissionMenu::myMenuHtml($this->adminUser->id);     // 我的菜单，HTML页面

        $menuParent = PermissionMenu::menuParent($this->m,$this->v,$this->path_address);
        array_multisort(array_column($menuParent, 'level'), SORT_DESC, $menuParent);
        $data['menu_parent'] = $menuParent;
        $data['current_date'] = LunarCalendar::currentDate();     // 当前日期

        return view($tpl, $data);
    }

    /**
     * Todo:: 响应页面提示
     * @param int $code 0 错误，1成功
     * @param string $msg
     * @param string $url
     * @param int $wait
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    protected function msgHtml($code=0,$msg='', $url = '', $wait = 3){
        if (!$url) {
            $url = $this->getRefererUrl();
        }
        if(!$msg){
            $msg = '错误';
        }
        return redirect('/admin/v1/common/msg')->with(['msg' => $msg, 'url' => $url, 'wait' => $wait, 'code' =>$code]);
    }

    /**
     * Todo::
     * @return string
     */
    private function getRefererUrl() {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $urlInfo = parse_url($_SERVER['HTTP_REFERER']);
            $query = isset($urlInfo['query']) ? '?' . $urlInfo['query'] : '';
            $url = $urlInfo['path'] . $query;
        } else {
            $url = '/';
        }
        return $url;
    }

    /**
     * Todo:: 响应
     * @param string $code
     * @param bool $status
     * @param string $message
     * @param array $data
     * @param int $type
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    protected function responseMsg($code='000000',$status=true,$message='Success',$data=[],$type=0){
        if($code == '000000'){
            $htmlCode = 1;
        }else{
            $htmlCode = 0;
        }
        $url = isset($data['url'])?$data['url']:"";
        $wait = isset($data['wait'])?$data['wait']:3;
        if($type == 1){
            return $this->msgHtml($htmlCode,$message,$url,$wait);
        }elseif($type == 2){
            if($code == '100000'){
                return response()->json(responseArray($code,$status,$message,$data),401);
            }else{
                return response()->json(responseArray($code,$status,$message,$data));
            }
        }else{
            if(request()->ajax()){
                if($code == '100000'){
                    return response()->json(responseArray($code,$status,$message,$data),401);
                }else{
                    return response()->json(responseArray($code,$status,$message,$data));
                }
            }else{
                return $this->msgHtml($htmlCode,$message,$url,$wait);
            }
        }
    }

    /**
     * Todo:: 写日志
     * @param $menus_id
     */
    private function _saveLog($menus_id)
    {
        $data = [];
        $data['menu_id'] = $menus_id;
        $data['method'] = request()->method();
        $data['query_string'] = $this->query_string;
        $data['admin_id'] = $this->adminUser->id;
        $data['ip'] = request()->ip();
        if (request()->method() == 'POST') {
            $data['data'] = json_encode(request()->post());
            if(isset(request()->post()['id'])){
                $data['primary_id'] = request()->post()['id'];
            }
            if(isset(request()->post()['info']['id'])){
                $data['primary_id'] = request()->post()['info']['id'];
            }
            // dd($data);
        }
        AdminLog::create($data);
    }

    /**
     * Todo:: 公共请求链接
     * @return array
     */
    private function publicRequest(){
        return array(
            'home/index',
            'common/msg',
            'images/upload',
            'admin_user/index/my_edit',
            'admin_user/index/my_pwd',
            'common/index/generate_key',
            'common/index/login_token',
        );
    }

}
